--[[配置start
time为多长时间单位为秒，count为在此时间内最多允许访问多少次
]]
wf_configs = { ip = { time = 1, count = 4 }, uuid = { time = 3, count = 6 } }
--配置end

dofile('conf/ngx-lua/lua/util.lua')
local tmp_shared_data = ngx.shared.tmp_shared_data
local wf_backlist = ngx.shared.wf_backlist

-- 加载黑名单
if not tmp_shared_data:get('isload') then
    local backlist = util:load_backlist()
    for i, j in ipairs(backlist) do
        wf_backlist:set(j, 'ok')
    end
    tmp_shared_data:set('isload', 1)
end

--[可注释]打印输出
for i, j in ipairs(tmp_shared_data:get_keys(0)) do
    if j ~= "isload" then
        ngx.say('<br/>')
        ngx.say('访问次数统计:key=', j, '->value=', tmp_shared_data:get(j))
    end
end

--[可注释]打印黑名单
for i, j in ipairs(wf_backlist:get_keys(0)) do
    ngx.say('<br/>')
    ngx.say('黑名单:key=', j, '->value=', wf_backlist:get(j))
end


-- 如果在黑名单直接拦截
ip = util.get_client_ip()
local is_in_backlist = wf_backlist:get(ip)
if is_in_backlist then
    util.exit('ip')
end
uuid = util.get_cookie_by_key('UUID')
is_in_backlist = wf_backlist:get(uuid)
if is_in_backlist then
    util.exit('uuid')
end

current_time = ngx.time()

--ip
ip_t1, _ = math.modf(current_time / wf_configs.ip.time)
ip_time = ip .. '|' .. ip_t1
local i = tmp_shared_data:get(ip_time)
if not i then
    tmp_shared_data:set(ip_time, 0, wf_configs.ip.time * 3)
    i = 0
end
tmp_shared_data:incr(ip_time, 1)
if i >= wf_configs.ip.count then
    wf_backlist:set(ip, 'ok')
    if not is_in_backlist then
        util.write_backlist(ip)
    end
    util.exit('ip')
end

-- uuid
uuid_t1 = math.modf(current_time / wf_configs.uuid.time)
uuid_time = uuid .. '|' .. uuid_t1
local j = tmp_shared_data:get(uuid_time)
if uuid ~= '' then
    if not j then
        tmp_shared_data:set(uuid_time, 0, wf_configs.uuid.time * 3)
        j = 0
    end
    tmp_shared_data:incr(uuid_time, 1)
    if j >= wf_configs.uuid.count then
        wf_backlist:set(uuid, 'ok')
        util.write_backlist(uuid)
        util.exit('uuid')
    end
end

-- 可注释
ngx.say('<br/><p style="color:green;">正常访问</p>')
